package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * app端用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        // 1.如果前端传来用户名和密码
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            String phone = dto.getPhone();
            String password = dto.getPassword();
            // 1.2 根据用户名去数据库查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "该app用户不存在");
            }
            // 1.3 如果存在,将前端传来的密码与数据库的密码校验
            String userPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!userPwd.equals(apUser.getPassword())) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 1.4 颁发token给用户
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("token", token);
            apUser.setPassword(null);
            apUser.setSalt(null);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }
        if (dto.getEquipmentId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "设备id不能为空");
        }
        // 用户选择不登录访问
        Map<String,Object> map = new HashMap<String,Object>();
        String token = AppJwtUtil.getToken(0L);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
